package edu.zjut.hjg.saas.kwmp.web.controller.admin;

import static edu.zjut.hjg.saas.kwmp.web.support.KwmpConstants.SESSION_NAME_USER;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import edu.zjut.hjg.saas.biz.model.Kindergarten;
import edu.zjut.hjg.saas.biz.model.User;
import edu.zjut.hjg.saas.biz.service.UserService;
import edu.zjut.hjg.saas.biz.service.exception.ServiceException;
import edu.zjut.hjg.saas.biz.support.RoleName;
import edu.zjut.hjg.saas.common.annotation.CookieSessionIn;
import edu.zjut.hjg.saas.common.annotation.RequestAttribute;
import edu.zjut.hjg.saas.common.util.ParameterUtil;
import edu.zjut.hjg.saas.kwmp.web.model.UserSession;

@Controller
@RequestMapping("/admin/user")
public class UserManageController {
    private static final Log log = LogFactory.getLog(UserManageController.class);

    @Autowired
    private UserService      userService;

    @RequestMapping("index.htm")
    public void index(@RequestAttribute Kindergarten app, Model model) {
        model.addAttribute("users", userService.listByRoleNameAndAppId(RoleName.TEACHER, app
                .getId()));
    }

    @RequestMapping("reset.htm")
    public void reset(@RequestAttribute Kindergarten app, Model model) {
        model.addAttribute("users", userService.listByRoleNameAndAppId(RoleName.TEACHER, app
                .getId()));
    }

    @CookieSessionIn(value = SESSION_NAME_USER, param = "session")
    @RequestMapping(value = "doReset.htm", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> doReset(@RequestAttribute Kindergarten app,
                                       @RequestParam("newPassword") String newPassword,
                                       @RequestParam("id") int id, UserSession session) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            userService.resetPassword(id, app.getId(), newPassword, session.getLoginId());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.put("success", false);
            result.put("message", "重置教师密码失败");
            return result;
        }
        result.put("success", true);
        return result;
    }

    @CookieSessionIn(value = SESSION_NAME_USER, param = "session")
    @RequestMapping(value = "create.htm", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> create(@RequestAttribute Kindergarten app, UserSession session,
                                      User user) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (!ParameterUtil.notBlank(user)) {
            result.put("success", false);
            result.put("message", "参数错误");
            return result;
        }
        user.setKindergarten(app);
        user.setRoleName(RoleName.TEACHER);
        // 默认密码为其账号
        user.setPassword(user.getLoginId());
        try {
            userService.create(user, session.getLoginId());
        } catch (ServiceException e) {
            log.warn(e.getMessage(), e);
            result.put("success", false);
            result.put("message", e.getErrorMessage());
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.put("success", false);
            result.put("message", "创建教师账号失败");
            return result;
        }
        result.put("success", true);
        result.put("user", user);
        return result;
    }

    @CookieSessionIn(value = SESSION_NAME_USER, param = "session")
    @RequestMapping("delete.htm")
    @ResponseBody
    public Map<String, Object> delete(@RequestAttribute Kindergarten app, UserSession session,
                                      @RequestParam("id") int id) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            userService.deleteByIdAndAppId(id, app.getId(), session.getLoginId());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.put("success", false);
            result.put("message", "删除教师账号失败");
            return result;
        }
        result.put("success", true);
        return result;
    }

    @CookieSessionIn(value = SESSION_NAME_USER, param = "session")
    @RequestMapping(value = "update.htm", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> update(@RequestAttribute Kindergarten app, UserSession session,
                                      Integer id, String name, String loginId) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (!ParameterUtil.notBlank(name, loginId, id)) {
            result.put("success", false);
            result.put("message", "参数错误");
            return result;
        }
        try {
            userService.update(id, loginId, name, app.getId(), session.getLoginId());
        } catch (ServiceException e) {
            log.warn(e.getMessage(), e);
            result.put("success", false);
            result.put("message", e.getErrorMessage());
            return result;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.put("success", false);
            result.put("message", "更新教师账号失败");
            return result;
        }
        result.put("success", true);
        return result;
    }
}
